package com.haiyou.common.plugin.util;


import com.haiyou.common.plugin.model.Plugin;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;

public class XMLParser {

    public static List<Plugin> getPluginList(String pluginPath) throws DocumentException {
        List<Plugin> list = new ArrayList<>();

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File(pluginPath));
        Element root = document.getRootElement();
        List<?> plugins = root.elements("plugin");
        for (Object pluginObj : plugins) {
            Element pluginEle = (Element) pluginObj;
            Plugin plugin = new Plugin();
            plugin.setName(pluginEle.elementText("name"));
            plugin.setJar(pluginEle.elementText("jar"));
            plugin.setClassName(pluginEle.elementText("class"));

            Map<String, String> map = new HashMap<>();
            Element properties = pluginEle.element("properties");
            if (properties != null) {
                Iterator property = properties.elementIterator("property");
                while (property.hasNext()) {
                    Element element = (Element) property.next();
                    Attribute nameAttr = element.attribute("name");
                    map.put(nameAttr.getValue(), element.getText());
                }
            }
            plugin.setConfigs(map);
            list.add(plugin);
        }
        return list;
    }
}